using System;
using System.Collections.Generic;
using Csla;
using Csla.Serialization;

namespace Northwind.BusinessObjects
{
    [Serializable]
    public class ProductList :
      ReadOnlyListBase<ProductList, ProductInfo>
    {
        #region Authorization Rules

        private static void AddObjectAuthorizationRules()
        {
            // TODO: add authorization rules
            //AuthorizationRules.AllowGet(typeof(ProductList), "Role");
        }

        #endregion

        #region Factory Methods

        public static void GetProductList(EventHandler<DataPortalResult<ProductList>> callback)
        {
            DataPortal.BeginFetch<ProductList>(callback);
        }

        public static void GetProductList(string filter, EventHandler<DataPortalResult<ProductList>> callback)
        {
            DataPortal.BeginCreate<ProductList>(filter, callback);
        }
#if !SILVERLIGHT
        public static ProductList GetProductList()
        {
            return DataPortal.Fetch<ProductList>();
        }

        public static ProductList GetProductList(string filter)
        {
            return DataPortal.Fetch<ProductList>(filter);
        }

#endif
        #endregion

        #region Data Access
#if !SILVERLIGHT
        private void DataPortal_Fetch()
        {
            DataPortal_Fetch(null);
        }

        private void DataPortal_Fetch(string filter)
        {
            var rlce = RaiseListChangedEvents;
            RaiseListChangedEvents = false;
            IsReadOnly = false;
            using (var ctx = Northwind.DataAccess.DalFactory.GetManager())
            {
                var dal = ctx.GetProvider<Northwind.DataAccess.IProductDal>();
                List<Northwind.DataAccess.ProductDto> list = null;
                if (filter == null)
                    list = dal.Fetch();
                else
                    list = dal.Fetch(filter);
                foreach (var item in list)
                    Add(DataPortal.FetchChild<ProductInfo>(item));
            }
            IsReadOnly = true;
            RaiseListChangedEvents = rlce;
        }

#endif
        #endregion
    }
}
